from rest_framework import response, viewsets, mixins, status

from business.models import Business
from business.serializers import BusinessSerializer
from servers.models import Server
from business.filter import BusinessFilter


class BusinessViewset(viewsets.ModelViewSet):
    """

    """
    queryset = Business.objects.all()
    serializer_class = BusinessSerializer
    # extra_perms_map = {  # get 权限
    #     "GET": ["products.view_product"]
    # }
    filter_class = BusinessFilter
    filter_fields = ('pid', )

    def destroy(self, request, *args, **kwargs):
        """
        删除业务线时做校验，业务线下全空时可以删除
        """
        result = {'status': 0}
        instance = self.get_object()
        if instance.pid == 0:
            # 顶级业务线，若没子项则删除
            if Business.objects.filter(pid__exact=instance.id).count() != 0:
                result['status'] = 1
                result['errmsg'] = '该业务线下还有子项'
                return response.Response(result, status.HTTP_400_BAD_REQUEST)
        else:
            # 二级业务线
            if Server.objects.filter(business_line__id__exact=instance.id).count() != 0:
                result['status'] = 1
                result['errmsg'] = '该业务线下还有服务器'
                return response.Response(result, status.HTTP_400_BAD_REQUEST)
        self.perform_destroy(instance)
        return response.Response(result, status.HTTP_200_OK)


class BusinessManageViewset(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    业务线管理接口
    list: 列出所有业务线
    """

    queryset = Business.objects.all()

    def list(self, request, *args, **kwargs):
        data = self.get_business()
        return response.Response(data)

    def get_node(self, business_obj):
        node = {
            'id': business_obj.id,
            'label': business_obj.name,
            'pid': business_obj.pid
        }
        return node

    def get_children(self, pid):
        result = []
        for obj in self.queryset.filter(pid=pid):
            result.append(self.get_node(obj))
        return result

    def get_business(self):
        result = []
        for obj in self.queryset.filter(pid=0):
            node = self.get_node(obj)
            node['children'] = self.get_children(obj.id)
            result.append(node)
        return result
